package com.huitong.common.core.handler;

import com.huitong.common.core.domain.Result;
import com.huitong.common.core.utils.StreamUtils;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 参数校验异常处理器
 *
 * @author fromdrowning
 * @date 2024/6/2 下午8:51
 */
@Slf4j
@RestControllerAdvice
public class ValidationHandler {

    /**
     * 自定义验证异常处理
     *
     * @param e 自定义验证异常
     * @return 错误提示
     */
    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException e) {
        log.error("自定义校验异常:{}", e.getMessage());
        return Result.error(StreamUtils.join(e.getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, " "));
    }

    /**
     * 自定义验证异常
     *
     * @param e 自定义验证异常
     * @return 错误提示
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
        log.error("自定义校验异常:{}", e.getMessage());
        return Result.error(StreamUtils.join(e.getConstraintViolations(), ConstraintViolation::getMessage, " "));
    }

    /**
     * 自定义验证异常
     *
     * @param e 自定义验证异常
     * @return 错误提示
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("自定义校验异常:{}", e.getMessage());
        return Result.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }
}
